package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.UrlConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelFormatUtil;
import cn.stylefeng.guns.sys.modular.system.controller.BaseFrontController;
import cn.stylefeng.guns.sys.modular.system.db4.model.result.ShopOwnerInfoResult;
import cn.stylefeng.guns.sys.modular.system.db5.mapper.UserDataMapper;
import cn.stylefeng.guns.sys.modular.system.db5.model.result.MenDianInfoResult;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyCwHuopeiMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyGoodsPayMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyGoodsPayParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyGoodsPayResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyGoodsPayShopOwerResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyGoodsPayService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.PushMsgService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import oshi.jna.platform.mac.SystemB;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2021-07-08
 */
@Service
public class BtyGoodsPayServiceImpl extends ServiceImpl<BtyGoodsPayMapper, BtyGoodsPay> implements BtyGoodsPayService {
    private Logger logger = LoggerFactory.getLogger(BtyGoodsPayServiceImpl.class);

    @Autowired
    private UserDataMapper userDataMapper;
    @Autowired
    private UrlConfig urlConfig;
    @Resource
    private DictService dictService;
    @Autowired
    private PushMsgService pushMsgService;
    @Resource
    private BtyCwHuopeiMapper cwHuopeiMapper;


    @Override
    public void add(BtyGoodsPayParam param) {
        BtyGoodsPay entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyGoodsPayParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public ResponseData update(BtyGoodsPayParam param) {
        BtyGoodsPay oldEntity = getOldEntity(param);
        BtyGoodsPay newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);

        //计算合计
//        BigDecimal decimal = (newEntity.getMainPay() == null ? BigDecimal.ZERO : newEntity.getMainPay())
//                .add(newEntity.getCanJu() == null ? BigDecimal.ZERO : newEntity.getCanJu())
//                .add(newEntity.getFaKuan() == null ? BigDecimal.ZERO : newEntity.getFaKuan())
//                .add(newEntity.getMissed() == null ? BigDecimal.ZERO : newEntity.getMissed());
//        newEntity.setSumMoney(decimal);
//
//        if (newEntity.getMainPay() == null) {
//            newEntity.setMainPay(BigDecimal.ZERO);
//        }
//        if (newEntity.getCanJu() == null) {
//            newEntity.setCanJu(BigDecimal.ZERO);
//        }
//        if (newEntity.getFaKuan() == null) {
//            newEntity.setFaKuan(BigDecimal.ZERO);
//        }
//        if (newEntity.getMissed() == null) {
//            newEntity.setMissed(BigDecimal.ZERO);
//        }
//        if (newEntity.getSumMoney() == null) {
//            newEntity.setSumMoney(BigDecimal.ZERO);
//        }

//        this.updateById(newEntity);
        newEntity.setUpdateTime(new Date());
        baseMapper.editById(newEntity);
        return ResponseData.success();
    }

    @Override
    public BtyGoodsPayResult findBySpec(BtyGoodsPayParam param) {
        return null;
    }

    @Override
    public List<BtyGoodsPayResult> findListBySpec(BtyGoodsPayParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyGoodsPayParam param, Map<String, ShopOwnerInfoResult> map) {

        //本月第几天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);

        //到本月第几天,默认11
        int endDay = 11;
        Dict dict1 = dictService.getOne(new QueryWrapper<Dict>().eq("code", "goods_pay_end_day"));

        if (dict1 != null) {
            if (StringUtils.isNumeric(dict1.getName())) {
                endDay = Integer.parseInt(dict1.getName());
            }
        }

        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        //店长，店长姓名
        List<BtyGoodsPayResult> dataList = page.getRecords();
        if (CollectionUtil.isNotEmpty(dataList)) {
            for (BtyGoodsPayResult result : dataList) {
                if (result.getYaoma() != null && !result.getYaoma().equals("")) {
                    if (map.get(result.getYaoma()) != null) {
                        result.setShopownerView(map.get(result.getYaoma()).getShopownerView());
                        result.setMobile(map.get(result.getYaoma()).getMobile());
                    }
                }

                //是否显示撤回按钮，当月11号以后不显示
                if (result.getStatus() != null && (result.getStatus() == 3 || result.getStatus() == 1)) {
                    if (monthDay > 11) {
                        //不显示
                        result.setRevokeView(0);
                    } else {
                        //显示
                        result.setRevokeView(1);
                    }
                }
            }

        }

        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData initData(String userName, BtyGoodsPayParam param) {

        //TODO-1 查找当前登录的会计下的店
        List<BtyGoodsPayResult> resultList = this.baseMapper.findAllShopInfoByUserName(userName, param.getMonth());

        //TODO-2 初始化数据
        if (CollectionUtil.isNotEmpty(resultList)) {
            for (BtyGoodsPayResult result : resultList) {
                BtyGoodsPay entity = new BtyGoodsPay();
                ToolUtil.copyProperties(result, entity);
                entity.setMonth(param.getMonth());
                this.save(entity);
            }
        } else {
            return ResponseData.error(1, "当前登录人当前月份目前没有要初始化数据的门店");
        }


        return ResponseData.success();
    }

    /**
     * 同步店名
     * @param userName
     * @param param
     * @return
     */
    @Override
//    public ResponseData synData(String userName, BtyGoodsPayParam param, Map<String, ShopOwnerInfoResult> mapResult) {
//
//        //TODO-2 获取需要同步的店名
//        List<Map> mapList = baseMapper.getMapList();
//        //获取店长列表
//        List<BtyGoodsPayShopOwerResult> list = this.baseMapper.getShopOwer();
//        String shopownerView = "";
////        String mobile = "";
//        BtyGoodsPay entity = new BtyGoodsPay();
//        List<BtyGoodsPay> list1 = new ArrayList<>();//有店长的店的列表
//
//        if (ToolUtil.isNotEmpty(mapList)){
//                for (Map map : mapList) {
//                    entity.setMonth(param.getMonth());//月份
//                    entity.setCwry(map.get("cwry").toString());//财务人员
//                    entity.setDm(map.get("dm").toString());//店名
//                    entity.setYaoma(map.get("yaoma").toString());//妖码
//                    entity.setMdbh(map.get("mdbh").toString());//门店编号
//                    entity.setCwm(map.get("cwm").toString());//财务码
//
//                    if (map.get("yaoma") != null && !map.get("yaoma").equals("")) {
//                        if (mapResult.get(map.get("yaoma")) != null){//获取店长
//                            shopownerView = mapResult.get(map.get("yaoma")).getShopownerView();//店长
////                            mobile = mapResult.get(map.get("yaoma")).getMobile();//电话
//                        }
//                        //获取该店店长列表
//                        List<BtyGoodsPayShopOwerResult> dzList = list.stream().filter(w -> w.getYaoma().equals(map.get("yaoma"))).collect(Collectors.toList());
//                        if (ToolUtil.isNotEmpty(dzList)){
//                            for (BtyGoodsPayShopOwerResult result : dzList) {
//                                //店长列表中存在shopownerView
//                                if (ToolUtil.isNotEmpty(shopownerView) && result.getXm().equals(shopownerView)){
//                                    entity.setDzName(result.getXm());//店长姓名
//                                    entity.setDzBh(result.getBh());//店长编号
//                                    list1.add(entity);
//                                }
//                            }
//                        }
//                    }
//
//                    //查询表中是否有该店
//                    int con = baseMapper.getCon(entity);
//                    if (con != 0){
//                        baseMapper.updateByYm(entity);
//                    }else {
//                        this.save(entity);
//                    }
//                    entity = new BtyGoodsPay();
//                }
//
//                if (ToolUtil.isNotEmpty(list1)){
//                    //获取对应店长为空的店
//                    List<BtyGoodsPay> payList = baseMapper.getDzList(list1, param.getMonth());
//                    for (BtyGoodsPay goodsPay : payList) {
//                        //妖码相同
//                        if (list1.stream().filter(w->w.getYaoma().equals(goodsPay.getYaoma())).findAny().isPresent()){
////                            goodsPay.setDzName();
//                        }
//                    }
//                }
//            }else {
//                return ResponseData.error(1, "当前登录人当前月份目前没有要初始化数据的门店");
//            }
//
//        return ResponseData.success();
//    }

    public ResponseData synData(String userName, BtyGoodsPayParam param, Map<String, ShopOwnerInfoResult> mapResult) {

        //TODO-2 获取需要同步的店名
        List<Map> mapList = baseMapper.getMapList();
        //获取店长列表
        List<BtyGoodsPayShopOwerResult> list = this.baseMapper.getShopOwer();
        String shopownerView = "";
        BtyGoodsPay entity = new BtyGoodsPay();
        List<BtyGoodsPay> list1 = new ArrayList<>();//有店长的店的列表

        if (ToolUtil.isNotEmpty(mapList)){
            for (Map map : mapList) {
                entity.setMonth(param.getMonth());//月份
                entity.setCwry(map.get("cwry").toString());//财务人员
                entity.setDm(map.get("dm").toString());//店名
                entity.setYaoma(map.get("yaoma").toString());//妖码
                entity.setMdbh(map.get("mdbh").toString());//门店编号
                entity.setCwm(map.get("cwm").toString());//财务码
                entity.setCreateTime(new Date());
                entity.setCreateUser(LoginContextHolder.getContext().getUserId());

                if (map.get("yaoma") != null && !map.get("yaoma").equals("")) {
                    if (mapResult.get(map.get("yaoma")) != null){//获取店长
                        shopownerView = mapResult.get(map.get("yaoma")).getShopownerView();//店长
                    }
                    //获取该店店长列表
                    List<BtyGoodsPayShopOwerResult> dzList = list.stream().filter(w -> w.getYaoma().equals(map.get("yaoma"))).collect(Collectors.toList());
                    if (ToolUtil.isNotEmpty(dzList)){
                        for (BtyGoodsPayShopOwerResult result : dzList) {
                            //店长列表中存在shopownerView
                            if (ToolUtil.isNotEmpty(shopownerView) && result.getXm().equals(shopownerView)){
                                entity.setDzName(result.getXm());//店长姓名
                                entity.setDzBh(result.getBh());//店长编号
                            }
                        }
                    }
                }

                list1.add(entity);

                entity = new BtyGoodsPay();
            }

            //查询表中存在的店
            List<BtyGoodsPay> list2 = baseMapper.getByList(list1, param.getMonth());
            if (ToolUtil.isNotEmpty(list2)){
                Map<String, BtyGoodsPay> payMap = list2.stream().collect(Collectors.toMap(s -> s.getYaoma().toString(), s -> s));
                List<BtyGoodsPay> list3 = new ArrayList<>();
                for (BtyGoodsPay goodsPay : list1) {
                    if (ToolUtil.isNotEmpty(goodsPay.getYaoma())){
                        if (ToolUtil.isEmpty(payMap.get(goodsPay.getYaoma()))){
                            list3.add(goodsPay);
                        }
                    }
//                    if (ToolUtil.isNotEmpty(goodsPay.getDzName())){//店长列表中存在shopownerView
//                        BtyGoodsPay btyGoodsPay = payMap.get(goodsPay.getYaoma());
//
//                        if (ToolUtil.isNotEmpty(btyGoodsPay.getDzName())){//数据库中没有店长
//                            btyGoodsPay.setDzName(goodsPay.getDzName());
//                            btyGoodsPay.setDzBh(goodsPay.getDzBh());
//                        }
//                    }
                }
                // 差集 (list1 - list2)数据库中不存在的店
//                List<BtyGoodsPay> list3 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
                //新增不存在的店
                if (ToolUtil.isNotEmpty(list3)){
                    for (BtyGoodsPay goodspay : list3) {
                        this.save(goodspay);
                    }
//                    this.saveBatch(list3);
                }

                for(int i = 0; i < list2.size();){
                    int i2 = (i + 150);
                    i2 = i2 > list2.size() ? list2.size() : i2;
                    List<BtyGoodsPay> sub = list2.subList(i, i2);
                    //修改通讯录中信息
                    this.baseMapper.updateByList(sub);
                    i = i2;
                }
                //修改存在的店
//                baseMapper.updateByList(list2);

                //店长不为空的店
                List<BtyGoodsPay> collect = list1.stream().filter(w -> ToolUtil.isNotEmpty(w.getDzName())).collect(toList());
                //数据库店长为空的店
                List<BtyGoodsPay> collect1 = list2.stream().filter(w -> ToolUtil.isEmpty(w.getDzName())).collect(toList());

                List<BtyGoodsPay> dzList = new ArrayList<>();//修改数据库店长
                if (ToolUtil.isNotEmpty(collect)){
                    for (BtyGoodsPay goodsPay : collect) {
                        //妖码相同
                        if (collect1.stream().filter(w->w.getYaoma().equals(goodsPay.getYaoma())).findAny().isPresent()) {
                            dzList.add(goodsPay);
                        }
                    }
                }

                for(int i = 0; i < dzList.size();){
                    int i2 = (i + 150);
                    i2 = i2 > dzList.size() ? dzList.size() : i2;
                    List<BtyGoodsPay> sub = dzList.subList(i, i2);
                    //修改通讯录中信息
                    this.baseMapper.updateDz(sub);
                    i = i2;
                }
               //修改店长姓名及编号
//                baseMapper.updateDz(dzList);
            }else {

                //新增不存在的店
                if (ToolUtil.isNotEmpty(list1)){
                    for (BtyGoodsPay goodspay : list1) {
                        this.save(goodspay);
                    }
                }
                //店长不为空的店
                List<BtyGoodsPay> collect = list1.stream().filter(w -> ToolUtil.isNotEmpty(w.getDzName())).collect(toList());
                for(int i = 0; i < collect.size();){
                    int i2 = (i + 150);
                    i2 = i2 > collect.size() ? collect.size() : i2;
                    List<BtyGoodsPay> sub = collect.subList(i, i2);
                    //修改通讯录中信息
                    this.baseMapper.updateDz(sub);
                    i = i2;
                }
            }

        }else {
            return ResponseData.error(1, "当前登录人当前月份目前没有要初始化数据的门店");
        }

        return ResponseData.success();
    }

    @Override
    public ResponseData send(BtyGoodsPayParam btyGoodsPayParam) {

        //TODO-1 修改状态为已发送
        BtyGoodsPay btyGoodsPay = this.getById(btyGoodsPayParam.getId());
        //已经通过的不能再次发送
        if (btyGoodsPay.getStatus() == 3) {
            return ResponseData.error(1, "已经通过货赔审核，不可再次发送");
        }
        //改状态为 1：已发送
        btyGoodsPay.setStatus(1);

        this.updateById(btyGoodsPay);

        List<MenDianInfoResult> allMenDianInfoList = userDataMapper.findAllMenDianInfo();
        Map<String, String> yaoMaDzMobileMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(allMenDianInfoList)) {
            for (MenDianInfoResult result : allMenDianInfoList) {
                yaoMaDzMobileMap.put(result.getBh(), result.getLxfs());
            }
        }

        String dzMobile = yaoMaDzMobileMap.get(btyGoodsPay.getYaoma());


        //TODO-2 推送公众号消息-改成异步发送，以免影响操作
        // pushMsgService.pushMsg(btyGoodsPay, dzMobile);


        //TODO-3 推送小妖app信息或小妖IM消息

        return ResponseData.success(btyGoodsPay);
    }


    @Override
    public ResponseData batchSend(BtyGoodsPayParam btyGoodsPayParam) {

        //发送成功的门店
        String failedSendName = "";
        int successNum = 0;
        int notSuccessNum = 0;

        //TODO-1 修改状态为已发送
        String[] strArray = btyGoodsPayParam.getIds().split(",");
        List<String> ids = Arrays.asList(strArray);

        for (String id : ids) {
            BtyGoodsPay btyGoodsPay = this.getById(id);
            //已经通过的不能再次发送
            if (btyGoodsPay.getStatus() == 3) {
                if (StringUtils.isBlank(failedSendName)) {
                    failedSendName = btyGoodsPay.getDm();
                } else {
                    failedSendName = failedSendName + "," + btyGoodsPay.getDm();
                }
                notSuccessNum = notSuccessNum + 1;
                continue;
            }
            //改状态为 1：已发送
            btyGoodsPay.setStatus(1);
            this.updateById(btyGoodsPay);
            successNum = successNum + 1;

            List<MenDianInfoResult> allMenDianInfoList = userDataMapper.findAllMenDianInfo();
            Map<String, String> yaoMaDzMobileMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(allMenDianInfoList)) {
                for (MenDianInfoResult result : allMenDianInfoList) {
                    yaoMaDzMobileMap.put(result.getBh(), result.getLxfs());
                }
            }

            String dzMobile = yaoMaDzMobileMap.get(btyGoodsPay.getYaoma());
            pushMsgService.pushMsg(btyGoodsPay, dzMobile);

        }

        if (notSuccessNum > 0) {
            return new SuccessResponseData(201, "发送成功数：" + successNum + "条,</br>发送失败数：" + notSuccessNum + "条,</br>发送失败门店：" + failedSendName + ",</br>失败原因：已经审核通过的数据不会再次发送", null);
        }


        //TODO-2 推送公众号消息

        //TODO-3 推送小妖app信息或小妖IM消息

        return ResponseData.success();
    }

    @Override
    public List<BtyGoodsPayResult> findAllData(BtyGoodsPayParam btyGoodsPayParam) {

        String[] strArray = btyGoodsPayParam.getYaoma().split(",");
        List<String> yaomas = Arrays.asList(strArray);
        btyGoodsPayParam.setParamList(yaomas);

        List<BtyGoodsPayResult> resultList = this.baseMapper.findAllData(btyGoodsPayParam);
        return resultList;
    }

    @Override
    public void submitDatas(BtyGoodsPayParam param) {

        BtyGoodsPay btyGoodsPay = this.getById(param.getId());

        btyGoodsPay.setBh1(param.getBh1());
        btyGoodsPay.setName1(param.getName1());
        btyGoodsPay.setMoney1(param.getMoney1());

        btyGoodsPay.setBh2(param.getBh2());
        btyGoodsPay.setName2(param.getName2());
        btyGoodsPay.setMoney2(param.getMoney2());

        btyGoodsPay.setBh2(param.getBh2());
        btyGoodsPay.setName2(param.getName2());
        btyGoodsPay.setMoney2(param.getMoney2());

        btyGoodsPay.setBh3(param.getBh3());
        btyGoodsPay.setName3(param.getName3());
        btyGoodsPay.setMoney3(param.getMoney3());

        btyGoodsPay.setBh4(param.getBh4());
        btyGoodsPay.setName4(param.getName4());
        btyGoodsPay.setMoney4(param.getMoney4());

        btyGoodsPay.setBh5(param.getBh5());
        btyGoodsPay.setName5(param.getName5());
        btyGoodsPay.setMoney5(param.getMoney5());

        //把状态改为 2：待审核
        btyGoodsPay.setStatus(2);

        this.baseMapper.updateById(btyGoodsPay);

    }

    /**
     * 审核:改变状态 3：已通过，4：已驳回
     */
    @Override
    public ResponseData audit(BtyGoodsPayParam param) {
        BtyGoodsPay btyGoodsPay = this.getById(param.getId());
        //TODO-1审核通过时，人员金额之和要和总金额相等
/*        if (param.getStatus() == 3) {
            BigDecimal renYuanSum = (btyGoodsPay.getMoney1() == null ? BigDecimal.ZERO : btyGoodsPay.getMoney1())
                    .add(btyGoodsPay.getMoney2() == null ? BigDecimal.ZERO : btyGoodsPay.getMoney2())
                    .add(btyGoodsPay.getMoney3() == null ? BigDecimal.ZERO : btyGoodsPay.getMoney3())
                    .add(btyGoodsPay.getMoney4() == null ? BigDecimal.ZERO : btyGoodsPay.getMoney4())
                    .add(btyGoodsPay.getMoney5() == null ? BigDecimal.ZERO : btyGoodsPay.getMoney5());

            BigDecimal sum = btyGoodsPay.getSumMoney() == null ? BigDecimal.ZERO : btyGoodsPay.getSumMoney();

            if (renYuanSum.compareTo(sum) != 0) {
                return ResponseData.error("审核未通过，各人员金额之和不等于货赔总金额");
            }
        }*/

        if(StringUtils.isBlank(btyGoodsPay.getDzName())){
            return ResponseData.error("请先选择店长，再审核");
        }else if (ToolUtil.isEmpty(btyGoodsPay.getSumMoney()) || btyGoodsPay.getSumMoney().compareTo(BigDecimal.ZERO) == 0){
            return ResponseData.error("货赔总金额不能为空或者不能为0");
        }

        //TODO-2修改状态 3：已通过，4：已驳回
        btyGoodsPay.setStatus(param.getStatus());
        this.updateById(btyGoodsPay);
        return ResponseData.success();
    }

    @Override
    public List<MenDianInfoResult> findAllMenDianInfo() {
        List<MenDianInfoResult> menDianInfoResultList = userDataMapper.findAllMenDianInfo();
        return menDianInfoResultList;
    }

    @Override
    public List<BtyGoodsPayResult> selectAllCwry(BtyGoodsPayParam param) {
        List<BtyGoodsPayResult> resultList = this.baseMapper.selectAllCwry(param);
        return resultList;
    }

    @Override
    public LayuiPageInfo findAllPageData(BtyGoodsPayParam param) {
        //TODO-1 获取查询结果
        Page pageContext = getPageContext();
        String[] strArray = param.getYaoma().split(",");
        List<String> yaomas = Arrays.asList(strArray);
        param.setParamList(yaomas);
        IPage page = this.baseMapper.findPageByParam(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response, BtyGoodsPayParam param, Map<String, ShopOwnerInfoResult> map) {

        try {
            logger.info(">>>>>>>>>>货赔-开始导出excel>>>>>>>>>>");
            BaseFrontController baseFrontController = new BaseFrontController();
            //TODO-1 获取查询结果
            List<BtyGoodsPayResult> resultList = this.baseMapper.findListByParam(param);
            if (CollectionUtil.isNotEmpty(resultList)) {
                for (BtyGoodsPayResult result : resultList) {
                    if (result.getYaoma() != null && !result.getYaoma().equals("")) {
                        if (map.get(result.getYaoma()) != null) {
                            result.setShopownerView(map.get(result.getYaoma()).getShopownerView());
                            result.setMobile(map.get(result.getYaoma()).getMobile());
                        }
                    }
                }
            }
            return baseFrontController.buildResponseEntity(export(resultList, param), "货赔报表-姓名：" + param.getLoginUserName() + "(日期:" + param.getMonth() + ")" + ".xls");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>货赔-导出excel 异常，原因为：" + e.getMessage());
        }
        return null;
    }

    @Override
    public ResponseData revoke(BtyGoodsPayParam param) {
        BtyGoodsPay btyGoodsPay = this.getById(param.getId());
        btyGoodsPay.setStatus(param.getStatus());
        this.updateById(btyGoodsPay);
        return ResponseData.success();
    }

    @Override
    public List<BtyGoodsPayShopOwerResult> selectShopOwer(BtyGoodsPayParam param) {
        List<BtyGoodsPayShopOwerResult> list=this.baseMapper.selectShopOwer(param);
        return list;
    }

    /**
     * 同步货赔总金额
     * @param date
     * @return
     */
    @Override
    public ResponseData editSumMoney(String date) {
        //获取货赔表中该月份数据
        List<Map> list = cwHuopeiMapper.getList(date);
        //获取货赔审核表中该月份数据(除已通过之外)
        List<Map> mapList = baseMapper.getList(date);
        Map<String, Map> hpMap = list.stream().collect(Collectors.toMap(s -> s.get("shop_name").toString(), s -> s));

        if (ToolUtil.isNotEmpty(mapList)){

            List<BtyGoodsPay> list1 = mapList.stream().map(h -> {
                Map map1 = hpMap.get(h.get("dm"));

                BtyGoodsPay btyGoodsPay = new BtyGoodsPay();
                if (ToolUtil.isNotEmpty(map1)){
                    btyGoodsPay.setSumMoney(new BigDecimal(map1.get("heji").toString()));//货赔总金额
                }
                btyGoodsPay.setDm(h.get("dm").toString());//店名
                btyGoodsPay.setMonth(date);//月份
                return btyGoodsPay;
            }).collect(Collectors.toList());

            //批量修改货赔审核表数据
            for(int i = 0; i < list1.size();){
                int i2 = (i + 150);
                i2 = i2 > list1.size() ? list1.size() : i2;
                List<BtyGoodsPay> sub = list1.subList(i, i2);
                this.baseMapper.edit(sub);
                i = i2;
            }
        }

        return ResponseData.success();
    }

    /**
     * 批量审核
     * @param btyGoodsPayParam
     * @return
     */
    @Override
    public ResponseData auditBatch(BtyGoodsPayParam btyGoodsPayParam) {
        //批量审核的门店
        int successNum = 0;//审核成功数量
        int notSuccessNum = 0;//审核失败数量
        String zeroDataName = "";//审核失败的店名

        //TODO-1
        String[] strArray = btyGoodsPayParam.getIds().split(",");
        List<String> ids = Arrays.asList(strArray);

        for (String id : ids) {
            BtyGoodsPay btyGoodsPay = this.getById(id);

            //请先选择店长，再审核
            if(StringUtils.isBlank(btyGoodsPay.getDzName())){
                if (StringUtils.isBlank(zeroDataName)) {
                    zeroDataName = btyGoodsPay.getDm();
                } else {
                    zeroDataName = zeroDataName + "," + btyGoodsPay.getDm();
                }
                notSuccessNum = notSuccessNum + 1;
                continue;
            }

            //货赔总金额为空或者为0，且财务扣款为空或者为0；不允许审核
            if(ToolUtil.isEmpty(btyGoodsPay.getSumMoney()) || btyGoodsPay.getSumMoney().compareTo(BigDecimal.ZERO) == 0){
                if (StringUtils.isBlank(zeroDataName)) {
                    zeroDataName = btyGoodsPay.getDm();
                } else {
                    zeroDataName = zeroDataName + "," + btyGoodsPay.getDm();
                }
                notSuccessNum = notSuccessNum + 1;
                continue;
            }
            //TODO-2修改状态 3：已通过，4：已驳回
            btyGoodsPay.setStatus(btyGoodsPayParam.getStatus());
            this.updateById(btyGoodsPay);
            successNum = successNum + 1;
        }

        if (notSuccessNum > 0) {
//            return new SuccessResponseData(201, "审核成功数：" + successNum + "条,</br>审核失败数：" + notSuccessNum + "条,</br>审核失败门店：" + zeroDataName + ",</br>失败原因：请先选择店长，再审核", null);
            return new SuccessResponseData(201, "审核成功数：" + successNum + "条,</br>审核失败数：" + notSuccessNum + "条,</br>失败原因：货赔总金额不能为空或者不能为0，且店长不能为空", null);
        }

        return ResponseData.success();
    }

    private InputStream export(List<BtyGoodsPayResult> list, BtyGoodsPayParam param) {
        logger.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        // 保留1000条数据在内存中
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式cell样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);
        // 报表体样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);


        //TODO-2 每一列字段名
        String[] titles = new String[]{"序号", "门店",
                "编码",
                "店长",
                "店长手机",
                "酱料酒水鱼平板货赔",
                "餐具货赔金额", "罚款金额",
                "漏扣金额",
                "货赔总金额",
                "月份",
                "状态",
                "姓名",
                "金额",
                "姓名",
                "金额",
                "姓名",
                "金额",
                "姓名",
                "金额",
                "姓名",
                "金额",
                "备注"};

        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000};

        //TODO-3 设置总标题内容，没有可略过
        //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        int firstRow = 1;
        int lastRow = 1;
        int firstCol = 1;
        int lastCol = 12;
        SXSSFRow row1 = sheet.createRow(0);
        SXSSFCell cell0 = row1.createCell(0);
        CellRangeAddress regionFist = new CellRangeAddress(firstRow - 1, lastRow - 1, firstCol - 1, lastCol - 1);
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名
        cell0.setCellValue("货赔报表-姓名：" + param.getLoginUserName() + "(日期:" + param.getMonth() + ")");
        cell0.setCellStyle(header);

        //TODO-4 设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);
        logger.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

        //酱料酒水鱼平板货赔
        BigDecimal mainPaySum = BigDecimal.ZERO;
        //餐具货赔金额
        BigDecimal canJuSum = BigDecimal.ZERO;
        //罚款金额
        BigDecimal faKuanSum = BigDecimal.ZERO;
        //漏扣金额
        BigDecimal missedSum = BigDecimal.ZERO;
        //货赔总金额
        BigDecimal sumMoneySum = BigDecimal.ZERO;

        //金额1
        BigDecimal money1Sum = BigDecimal.ZERO;
        //金额2
        BigDecimal money2Sum = BigDecimal.ZERO;
        //金额3
        BigDecimal money3Sum = BigDecimal.ZERO;
        //金额4
        BigDecimal money4Sum = BigDecimal.ZERO;
        //金额5
        BigDecimal money5Sum = BigDecimal.ZERO;

        //TODO-5 从第contentStartRow行开始为内容数据
        int contentStartRow = concentitleStartRow + 1;
        if (list != null && list.size() > 0) {
            int hangInx = 1;
            logger.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            for (int i = 0; i < list.size(); i++) {
                BtyGoodsPayResult result = list.get(i);
                SXSSFRow row = sheet.createRow(contentStartRow + i - 1);
                int j = 0;

                // 序号
                SXSSFCell cell = row.createCell(j++);
                setCellVal(hangInx, content, cell);

                //店名
                cell = row.createCell(j++);
                setCellVal(result.getDm(), content, cell);

                //财务码
                cell = row.createCell(j++);
                setCellVal(result.getCwm(), content, cell);

                //店长
                cell = row.createCell(j++);
                setCellVal(result.getShopownerView() == null ? "" : result.getShopownerView(), content, cell);

                //店长手机号
                cell = row.createCell(j++);
                setCellVal(result.getMobile() == null ? "" : result.getMobile(), content, cell);

                //酱料酒水鱼平板货赔
                cell = row.createCell(j++);
                setCellVal(result.getMainPay() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMainPay().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                mainPaySum = mainPaySum.add(result.getMainPay() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMainPay().setScale(4, BigDecimal.ROUND_UP)));


                //餐具货赔金额
                cell = row.createCell(j++);
                setCellVal(result.getCanJu() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getCanJu().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                canJuSum = canJuSum.add(result.getCanJu() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getCanJu().setScale(4, BigDecimal.ROUND_UP)));


                //罚款金额
                cell = row.createCell(j++);
                setCellVal(result.getFaKuan() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getFaKuan().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                faKuanSum = faKuanSum.add(result.getFaKuan() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getFaKuan().setScale(4, BigDecimal.ROUND_UP)));

                //漏扣金额
                cell = row.createCell(j++);
                setCellVal(result.getMissed() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMissed().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                missedSum = missedSum.add(result.getMissed() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMissed().setScale(4, BigDecimal.ROUND_UP)));

                //货赔总金额
                cell = row.createCell(j++);
                setCellVal(result.getSumMoney() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getSumMoney().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                sumMoneySum = sumMoneySum.add(result.getSumMoney() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getSumMoney().setScale(4, BigDecimal.ROUND_UP)));

                //月份
                cell = row.createCell(j++);
                setCellVal(result.getMonth(), content, cell);

                //状态
                cell = row.createCell(j++);
                if (result.getStatus() != null) {
                    if (result.getStatus() == 0) {
                        setCellVal("待发送", content, cell);
                    }
                    if (result.getStatus() == 1) {
                        setCellVal("已发送", content, cell);
                    }
                    if (result.getStatus() == 2) {
                        setCellVal("待审核", content, cell);
                    }
                    if (result.getStatus() == 3) {
                        setCellVal("已通过", content, cell);
                    }
                    if (result.getStatus() == 4) {
                        setCellVal("已驳回", content, cell);
                    }
                }


                //姓名1
                cell = row.createCell(j++);
                setCellVal(result.getName1() == null ? "" : result.getName1(), content, cell);

                //金额1
                cell = row.createCell(j++);
                setCellVal(result.getMoney1() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney1().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                money1Sum = money1Sum.add(result.getMoney1() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney1().setScale(4, BigDecimal.ROUND_UP)));

                //姓名2
                cell = row.createCell(j++);
                setCellVal(result.getName2() == null ? "" : result.getName2(), content, cell);

                //金额2
                cell = row.createCell(j++);
                setCellVal(result.getMoney2() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney2().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                money2Sum = money2Sum.add(result.getMoney2() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney2().setScale(4, BigDecimal.ROUND_UP)));


                //姓名3
                cell = row.createCell(j++);
                setCellVal(result.getName3() == null ? "" : result.getName3(), content, cell);

                //金额3
                cell = row.createCell(j++);
                setCellVal(result.getMoney3() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney3().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                money3Sum = money3Sum.add(result.getMoney3() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney3().setScale(4, BigDecimal.ROUND_UP)));

                //姓名4
                cell = row.createCell(j++);
                setCellVal(result.getName4() == null ? "" : result.getName4(), content, cell);

                //金额4
                cell = row.createCell(j++);
                setCellVal(result.getMoney4() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney4().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                money4Sum = money4Sum.add(result.getMoney4() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney4().setScale(4, BigDecimal.ROUND_UP)));

                //姓名5
                cell = row.createCell(j++);
                setCellVal(result.getName5() == null ? "" : result.getName5(), content, cell);

                //金额5
                cell = row.createCell(j++);
                setCellVal(result.getMoney5() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney5().setScale(4, BigDecimal.ROUND_UP)), content, cell);
                money5Sum = money5Sum.add(result.getMoney5() == null ? BigDecimal.ZERO : getBigDecimalVal(result.getMoney5().setScale(4, BigDecimal.ROUND_UP)));

                //备注
                cell = row.createCell(j++);
                setCellVal(result.getRemark() == null ? "" : result.getRemark(), content, cell);


                hangInx = hangInx + 1;

            }
            logger.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }

        int sumRowNum1 = contentStartRow + list.size();
        SXSSFRow rowSum = sheet.createRow(sumRowNum1 - 1);
        //制表人
        SXSSFCell cellSum0 = rowSum.createCell(0);
        cellSum0.setCellValue("总计");
        cellSum0.setCellStyle(content);

        SXSSFCell cellmainPaySum = rowSum.createCell(5);
        cellmainPaySum.setCellValue(mainPaySum.toString());
        cellmainPaySum.setCellStyle(content);

        SXSSFCell cellcanJuSum = rowSum.createCell(6);
        cellcanJuSum.setCellValue(canJuSum.toString());
        cellcanJuSum.setCellStyle(content);

        SXSSFCell cellfaKuanSum = rowSum.createCell(7);
        cellfaKuanSum.setCellValue(faKuanSum.toString());
        cellfaKuanSum.setCellStyle(content);

        SXSSFCell cellmissedSum = rowSum.createCell(8);
        cellmissedSum.setCellValue(missedSum.toString());
        cellmissedSum.setCellStyle(content);

        SXSSFCell cellsumMoneySum = rowSum.createCell(9);
        cellsumMoneySum.setCellValue(sumMoneySum.toString());
        cellsumMoneySum.setCellStyle(content);

        SXSSFCell cellmoney1Sum = rowSum.createCell(titles.length - 10);
        cellmoney1Sum.setCellValue(money1Sum.toString());
        cellmoney1Sum.setCellStyle(content);

        SXSSFCell cellmoney2Sum = rowSum.createCell(titles.length - 8);
        cellmoney2Sum.setCellValue(money2Sum.toString());
        cellmoney2Sum.setCellStyle(content);

        SXSSFCell cellmoney3Sum = rowSum.createCell(titles.length - 6);
        cellmoney3Sum.setCellValue(money3Sum.toString());
        cellmoney3Sum.setCellStyle(content);

        SXSSFCell cellmoney4Sum = rowSum.createCell(titles.length - 4);
        cellmoney4Sum.setCellValue(money4Sum.toString());
        cellmoney4Sum.setCellStyle(content);

        SXSSFCell cellmoney5Sum = rowSum.createCell(titles.length - 2);
        cellmoney5Sum.setCellValue(money5Sum.toString());
        cellmoney5Sum.setCellStyle(content);


        //TODO 制表人、时间
        //所在行
        int sumRowNum2 = sumRowNum1 + 1;
        SXSSFRow rowEnd = sheet.createRow(sumRowNum2 + 1);
        //制表人
        SXSSFCell cellEnd0 = rowEnd.createCell(0);
        cellEnd0.setCellValue("制表人：" + LoginContextHolder.getContext().getUser().getName());
        //制表时间
        SXSSFCell cellEnd1 = rowEnd.createCell(titles.length - 1);
        cellEnd1.setCellValue(DateUtil.getNow());

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null) {
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream1;
    }

    private BigDecimal getBigDecimalVal(BigDecimal value) {
        if (value.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        return value;
    }


    private void setCellVal(Object j, CellStyle content, SXSSFCell cell) {
        cell.setCellValue(j.toString());
        cell.setCellStyle(content);
    }

    private Serializable getKey(BtyGoodsPayParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyGoodsPay getOldEntity(BtyGoodsPayParam param) {
        return this.getById(getKey(param));
    }

    private BtyGoodsPay getEntity(BtyGoodsPayParam param) {
        BtyGoodsPay entity = new BtyGoodsPay();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
